#include <stdio.h>
#include <string.h>
#include "stdlib.h"
#include "hash.h"

struct __result{
    HashEntry* entry;
    HASH_RESULT result;
};
typedef struct __result result;

result create_entry(const char *key, int value, HashEntry* next) {
    result res; 
    res.result = HASH_ERROR;
    res.entry = (HashEntry*) malloc(sizeof(HashEntry));
    if(!res.entry) return res;
    res.entry -> key.str_value = (char*) malloc(strlen(key) + 1);
    if(!res.entry -> key.str_value) return res;
    strcpy(res.entry -> key.str_value, key);
    res.entry -> value.int_value = value;
    res.entry -> next = next;
    res.result = HASH_OK;
    return res;
}

HASH_RESULT hash_add_int(HashTable *table, const char *key, int value ){
    int x = hash_string(key) % table -> size;
    if(table -> bucket[x] == NULL) {
        result res = create_entry(key, value, NULL);
        if(res.result != HASH_OK) return res.result;
        table -> bucket[x] = res.entry;
        return HASH_ADDED;
    }
    HashEntry* cur = table -> bucket[x];
    while(cur) {
        if(!strcmp(cur -> key.str_value, key)) {
            if(cur -> value.int_value != value) {
                cur -> value.int_value = value;
                return HASH_REPLACED_VALUE;
            }
            return HASH_ALREADY_ADDED;
        }
        cur = cur -> next;
    }
    result res = create_entry(key, value, table -> bucket[x]);
    if(res.result != HASH_OK) return res.result;
    table -> bucket[x] = res.entry;
    return HASH_ADDED;
}